﻿using System;
using System.ComponentModel;
using System.Deployment.Application;
using System.Windows.Forms;

namespace AutoTAU
{
    internal static class UpdateManager
    {
        /// <summary>
        /// Automatic Updates
        /// </summary>
        private static bool autoUpdate;

        /// <summary>
        /// Time of last automatic update
        /// </summary>
        public static DateTime LastUpdate = DateTime.MinValue;

        public static bool AutoUpdate
        {
            get { return autoUpdate; }

            set
            {
                autoUpdate = value;

                // (Un)Register wifi event handler
                if (value)
                {
                    WifiAuthManager.WifiAuthEvent += UpdateWifiAuthEventHandler;
                }
                else
                {
                    WifiAuthManager.WifiAuthEvent -= UpdateWifiAuthEventHandler;
                }
            }
        }

        public static void CurrentDeployment_CheckForUpdateCompleted(object sender, CheckForUpdateCompletedEventArgs e)
        {
            if (e.UpdateAvailable)
            {
                // Start an asynchronous download and installation of the new update
                ApplicationDeployment.CurrentDeployment.UpdateAsync();
            }
        }

        public static void CurrentDeployment_UpdateCompleted(object sender, AsyncCompletedEventArgs e)
        {
            if ((e.Cancelled == false) && (e.Error == null))
            {
                // Update successfully installed, restart silently
                Application.Restart();
            }
        }

        /// <summary>
        /// Try to check for an update and apply it if it is found.
        /// Returns true or false to indicate whether a new version was found and installed.
        /// On error throws exception.
        /// </summary>
        public static bool TryToUpdate()
        {
            try
            {
                LastUpdate = DateTime.Now;
                return ApplicationDeployment.CurrentDeployment.Update();
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// Try to check for an update.
        /// If an update is found, the method applies the update and restarts the application.
        /// </summary>
        public static void AsyncUpdate()
        {
            try
            {
                ApplicationDeployment.CurrentDeployment.CheckForUpdateAsync();
                LastUpdate = DateTime.Now;
            }
            catch
            {
            }
        }

        /// <summary>
        /// Handle events that indicate that the computer may be online so we can decide if we want to check for updates.
        /// </summary>
        /// <param name="status">Wifi status</param>
        /// <param name="title">Message title</param>
        /// <param name="msg">Message body</param>
        private static void UpdateWifiAuthEventHandler(WifiStatus status, string title, string msg, bool critical)
        {
            if ((status == WifiStatus.Success) || (status == WifiStatus.ConnectedToAnotherNetwork))
            {
                // We're online
                // See if it's been long enough since the last update
                if ((DateTime.Now - LastUpdate).Days >= 1)
                {
                    // Asynchronous update
                    AsyncUpdate();
                }
            }
        }
    }
}